package com.ximu.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximu.common_utlis.jwt.JwtUtil;
import com.ximu.common_utlis.result.Result;

import com.ximu.user.entity.User;
import com.ximu.user.entity.UserVo;
import com.ximu.user.mapper.UserMapper;
import com.ximu.user.service.AlipayService;
import com.ximu.user.service.LoginService;
import com.ximu.user.service.UserService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ximu
 * @since 2023-03-18
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户中心接口")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginService loginService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    @Qualifier("alipayService")
    private AlipayService alipayService;

//    @GetMapping("findAllUser")
//    //@PreAuthorize("hasAuthority('test')")
//    @ApiOperation(value = "查询所有用户")
//    public Result findAllUser(){
//        List<User> list = userService.list(null);
//        return Result.ok().data("list",list).message("成功");
//    }

    @ApiOperation(value = "查询个人信息")
    @PostMapping("findOneUser")
    public Result findOneUser(@RequestHeader("Authorization") String token){

        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            User user = userMapper.selectById(subject);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            userVo.setPassword(null);

            return Result.ok().data("user",userVo).message("成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("查询失败，检查是否登录");
    }

    @ApiOperation(value = "支付宝充值")
    @PostMapping("topup")
    public Result topup(@RequestHeader("Authorization") String token,int topup){

        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            User user = userMapper.selectById(subject);
            double balance = user.getBalance().doubleValue() + topup;
            user.setBalance(BigDecimal.valueOf(balance));
            int rs = userMapper.updateById(user);
            String pays = alipayService.appPagePay(String.valueOf(user.getUserId()), topup, "充值");
            if (rs>0){
                return Result.ok().message("充值成功，当前余额为："+balance).data("返回页面",pays);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("充值失败");
    }

    @ApiOperation(value = "支付宝支付")
    @PostMapping("topupzf")
    public Result topupzf(@RequestHeader("Authorization") String token,int topup){

        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            User user = userMapper.selectById(subject);
            String pays = alipayService.appPagePay(String.valueOf(user.getUserId()), topup, "支付");
            return Result.ok().message("支付成功").data("返回页面",pays);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("支付失败");
    }


    @ApiOperation(value = "余额支付")
    @PostMapping("balance")
    public Result balance(@RequestHeader("Authorization") String token,int balance){

        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            User user = userMapper.selectById(subject);
            double balance2 = user.getBalance().doubleValue() - balance;
            user.setBalance(BigDecimal.valueOf(balance2));
            int rs = userMapper.updateById(user);
            if (rs>0){
                return Result.ok().message("支付成功，当前余额为："+balance);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("支付失败");
    }


    @PostMapping("login")
    @ApiOperation(value = "登录")
    public Result login(@RequestBody User user){
        System.out.println(user.toString());
        String jwt = loginService.login(user);

        return Result.ok().data("token",jwt).message("登录成功");
    }

    @PostMapping("logout")
    @ApiOperation(value = "注销")
    public Result logout(@RequestHeader("Authorization") String token){
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            loginService.logout(Integer.parseInt(subject));
            return Result.ok().message("注销成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("注销失败，检查是否登录");


    }

    @PostMapping("register")
    @ApiOperation(value = "注册")
    public Result register(@RequestBody User user){
        //判断用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(User::getUserName, user.getUserName());
        User user1 = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user1)){
            String password = user.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(password);
            user.setPassword(encode);
            user.setUserId(null);
            user.setBalance(BigDecimal.valueOf(0));
            user.setVip(0);
            user.setIntegral(0);
            user.setVipDate(null);
            int rs = userMapper.insert(user);
            if(rs>0){
                User rsuser = userMapper.selectById(user.getUserId());
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(rsuser,userVo);
                userVo.setPassword(null);
                return Result.ok().data("user",userVo).message("注册成功，新用户信息如下");
            }else{
                return Result.error().message("注册失败");
            }
        }else {
            return Result.error().message("该用户名已存在");
        }


    }


    @PostMapping("update")
    @ApiOperation(value = "修改个人信息,用户只能改名称和头像，头像从图床回调这个函数就行")
    public Result update(@RequestBody User user,@RequestHeader("Authorization") String token) {

        //判断用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(User::getUserName, user.getUserName());
        User user1 = userMapper.selectOne(queryWrapper);
        try {
            //获取id
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            //查询信息
            User updateUser = userMapper.selectById(subject);
            //修改部分字段
            updateUser.setIntegral(user.getIntegral());
            updateUser.setUserName(user.getUserName());
            updateUser.setImg(user.getImg());
            int rs = userMapper.updateById(updateUser);
            if (rs > 0) {
                User rsuser = userMapper.selectById(user.getUserId());
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(rsuser, userVo);
                userVo.setPassword(null);
                return Result.ok().data("user", userVo).message("修改成功，新用户信息如下");
            } else {
                return Result.error().message("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.error().message("修改失败lost");
    }



}

